<!--机构奖惩 分配-->
<template>
  <div>
    <div>
      <div class="sub-title">
        <div class="content"><span>奖惩项：{{ rewardpunishItem && rewardpunishItem.bonusItemName}}</span><span>奖惩时间：{{rewardpunishItem && rewardpunishItem.actDate}}</span></div>
      </div>
      <div class="menu-left flex-l-r">
        <el-button type="primary" @click="save" :disabled="!isEdit">保存</el-button>
        <el-button type="primary" plain @click="goBack(false)">返回</el-button>
      </div>
      <div class="divide"></div>
      <div class="menu-left align-right">
         <span class="txt-bold">奖惩金额:</span><span class="txt-amount">{{rewardpunishItem && rewardpunishItem.amount}}</span>
         <span class="txt-bold">剩余金额:</span><span class="txt-amount">{{remainAmount}}</span>
         <el-button type="success" plain @click="equalDistribute" class="mg-l15" :disabled="!isEdit">平均分配</el-button>
      </div>
      <el-table :data="tableData"
                v-loading="loading"
                :summary-method="getSummaries"
                ref="tableRef"
                class="edit-table"
                show-summary
                border
                :height="`calc(100vh - 270px )`">
        <el-table-column
          width="60px"
          prop=""
          label="序号"
          align="center"
        >
          <template slot-scope="scope">
            {{(page.currentPage - 1) * page.pageSize + scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
          prop="personName"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="personCode"
          label="员工编号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="amount"
          label="分配金额"
          align="center"
        >
          <template slot-scope="scope">
              <el-input-number v-if="isEdit" :controls="false" v-model="scope.row.amount" placeholder="请输入"></el-input-number>
              <span v-else class="col-span">{{scope.row.amount}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import {fetchListUser,fetchListUserDivided, saveUserList} from '@/api/bonus/dataorgrewardpunish'
export default{
  name:"decompose",
  components:{
  },
  watch:{
    tableData:{
      handler(newV,oldV){

        let sum = 0 ;
        const values = this.tableData.map(item => Number(item.amount));
        if (!values.every(value => isNaN(value))) {
          sum = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
       this.remainAmount = this.rewardpunishItem.amount - sum

      },
      deep:true,
      immediate:true
    }
  },
  data() {
    return {
      loading:false,
      page:{
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      tableData: [],
      rewardpunishItem:{},
      remainAmount: 0,
      isEdit:true,
    }
  },
  computed: {

  },
  created(){

  },
  methods:{
    init(data){
      this.rewardpunishItem = data ;
      if (this.rewardpunishItem.assignmentStatus == '已分配'){//已分配
         this.onLoadDivided() ;
         this.isEdit = false ;
      }else{ //未分配
        this.onLoad() ;
        this.isEdit = true  ;
      }
    },
    onLoadDivided(){
      this.loading = true ;
      fetchListUserDivided({ deptIdPenalty:this.rewardpunishItem.id}).then(res=>{
        if (res.data.code == 0){
          this.tableData =  res.data.data.records ;
          this.$nextTick(()=>{
            this.$refs.tableRef.doLayout() ;
          })
        }else{
          this.$message.error(res.data.msg)
        }
        this.loading = false ;
      }).catch(()=>{
        this.loading = false ;
      })
    },
    onLoad(){
      this.loading = true ;
      fetchListUser({bonusDeptId:this.rewardpunishItem.bonusDeptId}).then(res=>{
        if (res.data.code == 0){
          this.tableData =  res.data.data ;
          this.$nextTick(()=>{
            this.$refs.tableRef.doLayout() ;
          })
        }else{
          this.$message.error(res.data.msg)
        }
        this.loading = false ;
      }).catch(()=>{
        this.loading = false ;
      })
    },

    goBack(refresh){
      this.$emit('close',refresh)
    },
    equalDistribute(){
      let everyAmount = (this.rewardpunishItem.amount / this.tableData.length).toFixed(2) //每人金额
      this.tableData.map(item=>{
        item.amount = everyAmount ;
      })
      this.remainAmount = this.rewardpunishItem.amount - everyAmount * this.tableData.length //剩余金额
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0 || index === 1) {
          sums[index] = '-';
          return;
        }else if (index === 2){
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = '-';
        }
      });

      return sums;
    },
    save(){
      this.loading = true ;
      this.tableData.map(item=>{
        item.deptIdPenalty = this.rewardpunishItem.id ;
      })
      saveUserList(this.tableData).then(res=>{
        if (res.data.code == 0){
          this.$message.success('保存成功')
          this.goBack(true)
        }else{
          this.$message.error('保存失败')
        }
        this.loading = false ;
      }).catch(err=>{
        this.loading = false ;
      })
    },

  }
}
</script>
<style scoped>
.col-span{display: inline-block;padding: 4px}
</style>
